# DFI provides an OPEN API
require 'date'

module Shin
  module Data
    class Dfi
      
      def new
        self
      end
      
      # Search (on title)
      def search(params={})
        raise MissingArgument, "You are missing the argument 'title' which is required to use this source." unless params[:title] != ""
        params[:year] ||= nil

        # Response
        if params[:year] != nil
          response = Base.get('http://nationalfilmografien.service.dfi.dk/movie.svc/list?titlecontains=' + URI.encode(params[:title]) + '&startyear='+(params[:year] - 1).to_s+'&endyear='+(params[:year] + 1).to_s)
        else
          response = Base.get('http://nationalfilmografien.service.dfi.dk/movie.svc/list?titlecontains=' + URI.encode(params[:title]))
        end

        raise HTTPError, "The response didn't have a 200 HTTP Code. It had #{response.code}." unless response.code == 200
        
        # Nokogiri parse
        doc = Nokogiri::XML(response.body) rescue nil
        
        # Can't be nil
        if doc != nil
          doc.remove_namespaces!
          
          @array = []
          doc.xpath("//MovieListItems/MovieListItem").each do |item|

            # If year is nil then return all
            if params[:year] != nil
              return {id: item.xpath('./ID').text.to_i, name: item.xpath('./Name').text, url: item.xpath('./Url').text}.to_hashugar
            else
              @array << {id: item.xpath('./ID').text.to_i, name: item.xpath('./Name').text, url: item.xpath('./Url').text}
            end

          end
          
          @array.to_hashugar
        else
          raise NotValid, "Nokogiri failed to parse the XML."
        end
        
      end
      
      # Info
      def info(params={})
        raise MissingArgument, "You are missing the argument 'id' which is required to use this source." unless params[:id] != ""
        
        # Response
        response = Base.get('http://nationalfilmografien.service.dfi.dk/movie.svc/' + params[:id].to_s)
        raise HTTPError, "The response didn't have a 200 HTTP Code. It had #{response.code}." unless response.code == 200
        
        # Nokogiri parse
        data = response.parsed_response['MovieItem'] rescue nil
        
        if data != nil
          {id: data['ID'].to_i, title: data['Title'], original_title: data['OriginalTitle'].strip, age_limit: data['Censorship'], url: data['Url'], description: data['Description']}.to_hashugar
        else
          raise NotValid, "Nokogiri failed to parse the XML."
        end
      end
      
      # Errors
      class NotValid         < StandardError; end
      class HTTPError        < StandardError; end
      class MissingArgument  < StandardError; end
      
    end
  end
end